package com.task.config;

import com.task.job.ScheduelJob;
import org.quartz.Trigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * @Author Tanyu
 * @Date 2020/6/11 15:27
 * @Description
 * @Version 1.0
 */
@Configuration
public class QuartzConfigure {

  @Bean(name = "ScheduelJob")
  public MethodInvokingJobDetailFactoryBean detailFactoryBean(ScheduelJob task){
    MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
    /*
     * 是否并发执行
     * true，执行下一个任务;false，等待上一个任务执行完后，再开始执行
     */
    jobDetail.setConcurrent(false);
//设置定时任务的名字
    jobDetail.setName("测试Quartz");
    //设置任务的分组，这些属性都可以在数据库中，在多任务的时候使用
    jobDetail.setGroup("group1");
    //为需要执行的实体类对应的对象
    jobDetail.setTargetObject(task);
    /*
     * sayHello为需要执行的方法
     * 通过这几个配置，告诉JobDetailFactoryBean我们需要执行定时执行ScheduleTask类中的sayHello方法
     */
    jobDetail.setTargetMethod("task");
    return jobDetail;
  }

  @Bean(name = "jobTrigger")
public CronTriggerFactoryBean cronTriggerFactoryBean(MethodInvokingJobDetailFactoryBean jobDetail){
  CronTriggerFactoryBean trigger = new CronTriggerFactoryBean();
  trigger.setJobDetail(jobDetail.getObject());
  //初始化的cron表达式(每天23：59：59触发)
  trigger.setCronExpression("0/2 * * * * ?");
  //trigger的name
  trigger.setName("测试");
  return trigger;
}

  @Bean(name = "scheduler")
  public SchedulerFactoryBean schedulerFactoryBean(Trigger trigger){
    SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
    //用于quartz集群，QuartzScheduler启动时更新已存在的job
    factoryBean.setOverwriteExistingJobs(true);
    //延时启动，应用启动1秒后
    factoryBean.setStartupDelay(1);
    //注册触发器
    factoryBean.setTriggers(trigger);
    return factoryBean;
  }
}
